import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import type { ChatMessage } from '@/type/index'

export const useChatMessageStore = defineStore('ChatMessage', () => {
    const chatMessage = ref<ChatMessage[]>([])

    //获取聊天消息
    function getChatMessage() {
        chatMessage.value = JSON.parse(localStorage.getItem('chatMessage') as string) || []
        return chatMessage.value
    }

    // 添加聊天消息
    function addChatMessage(message: ChatMessage) {
        chatMessage.value.push(message)
    }

    // 获取最后一条聊天消息
    const lastChatMessage = computed(() => {
        return chatMessage.value[chatMessage.value.length - 1]
    })

    //删除某一个聊天消息
    function delChatMessage(message: ChatMessage, index: number) {
        const { id, created_at } = message
        if (id) {
            chatMessage.value = chatMessage.value.filter(item => item.id !== id)
        } else if (created_at) {
            chatMessage.value = chatMessage.value.filter(item => item.created_at !== created_at)
        } else if (index) {
            chatMessage.value.splice(index, 1)
        }
    }

    // 清空聊天消息
    function clearChatMessage() {
        chatMessage.value = []
    }

    return {
        chatMessage,
        getChatMessage,
        addChatMessage,
        lastChatMessage,
        delChatMessage,
        clearChatMessage
    }
})